package com.matchmealpha;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity implements OnClickListener {

	public static  LoginActivity THIS_INSTANCE;
	protected EditText username;
	protected EditText password;
	protected Button createAccountButton;
	protected Button loginButton;
	protected ProgressDialog loadingDialog;
	protected TextView errorMessege;

	private static final String LOGIN_SUCCESS = "success";
	private static final String LOGIN_FAILURE = "failed";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		THIS_INSTANCE = this;
		super.onCreate(savedInstanceState);
		
		SharedPreferences settings = getSharedPreferences(
				"matchme_preferences", 0);
		String sessionid = settings.getString("sessionid", "");
		
		if(!sessionid.equals(""))
		{
			Intent intent = new Intent(LoginActivity.this,
					MatchMeTabWidget.class);
			LoginActivity.this.startActivity(intent);	
		}
		
		loadingDialog = new ProgressDialog(this);
		loadingDialog.setTitle("Authenticating...");
		
		
		initLayout();
		initListener();
	}

	private void initLayout() {
		setContentView(R.layout.login_view);
		createAccountButton = (Button) this
				.findViewById(R.id.LoginCreateAccountButton);
		loginButton = (Button) this.findViewById(R.id.LoginButton);
		username = (EditText) this.findViewById(R.id.LoginUsername);
		password = (EditText) this.findViewById(R.id.LoginPassword);
		errorMessege = (TextView) this.findViewById(R.id.LoginErrorTextView);
	}

	private void initListener() {
		createAccountButton.setOnClickListener(this);
		loginButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case (R.id.LoginButton):
			InputMethodManager inputManager = (InputMethodManager) this
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.hideSoftInputFromWindow(this.getCurrentFocus()
					.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			loadingDialog.show();
			new LoginTask().execute(username.getText().toString(), password
					.getText().toString());
			// Intent intent = new Intent(this,MatchMeTabWidget.class);
			// this.startActivity(intent);
			/*
			 * View view = RecentGroup.recentGroup.getLocalActivityManager()
			 * .startActivity("SettingActivity",
			 * intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView();
			 * RecentGroup.recentGroup.replaceView(view);
			 */
			break;

		case (R.id.LoginCreateAccountButton):
			InputMethodManager inputManager2 = (InputMethodManager) this
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager2.hideSoftInputFromWindow(this.getCurrentFocus()
					.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			Intent intent2 = new Intent(this, CreateAccountActivity.class);
			intent2.putExtra("username", username.getText().toString());
			intent2.putExtra("password", password.getText().toString());
			this.startActivity(intent2);
			/*
			 * View view2 = RecentGroup.recentGroup.getLocalActivityManager()
			 * .startActivity("CreateAccountActivity",
			 * intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
			 * .getDecorView(); RecentGroup.recentGroup.replaceView(view2);
			 */

			break;
		}
	}

	private class LoginTask extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... data) {

			HttpRequest req = new HttpRequest();
			String response;
			response = req.sendPost(MatchMeTabWidget.MM_SERVER + "/login_user",
					"username=" + data[0] + "&" + "password=" + data[1]);

			if (LoginActivity.LOGIN_SUCCESS.equals(response)
					&& req.getSessionID() != null) {

				SharedPreferences settings = getSharedPreferences(
						"matchme_preferences", 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("sessionid", req.getSessionID());
				editor.putString("username", username.getText().toString());
				// Toast.makeText(LoginActivity.this, req.getSessionID() + "",
				// Toast.LENGTH_LONG);
				// Commit the edits!
				editor.commit();
				return true;
			} else if (LoginActivity.LOGIN_FAILURE.equals(response))
				return false;
			else
				return false;
		}

		protected void onPostExecute(Boolean result) {
			THIS_INSTANCE.loadingDialog.cancel();
			if (result) {
				Intent intent = new Intent(LoginActivity.this,
						MatchMeTabWidget.class);
				LoginActivity.this.startActivity(intent);
			} else {
				errorMessege.setText("Unable to authenticate. Try Again");
				Log.d("LOGIN ACTIVITY", "FAILED");
				// Toast.makeText(LoginActivity.this, "Login Failed",
				// Toast.LENGTH_LONG);
			}
		}
	}
}
